import { ValidationChain, body, param, query } from 'express-validator';
import { UserRole } from '../../types/prisma-types';
import { withValidation, createValidation } from '../validation';

const userCreationRules: ValidationChain[] = [
  body('email')
    .isEmail()
    .withMessage('Invalid email format'),
  body('password')
    .isLength({ min: 6 })
    .withMessage('Password must be at least 6 characters long'),
  body('name')
    .trim()
    .isLength({ min: 2 })
    .withMessage('Name must be at least 2 characters long'),
  body('role')
    .isIn(Object.values(UserRole))
    .withMessage('Invalid role')
];

const userUpdateRules: ValidationChain[] = [
  body('email')
    .optional()
    .isEmail()
    .withMessage('Invalid email format'),
  body('password')
    .optional()
    .isLength({ min: 6 })
    .withMessage('Password must be at least 6 characters long'),
  body('name')
    .optional()
    .trim()
    .isLength({ min: 2 })
    .withMessage('Name must be at least 2 characters long'),
  body('role')
    .optional()
    .isIn(Object.values(UserRole))
    .withMessage('Invalid role')
];

const userIdRules: ValidationChain[] = [
  param('id')
    .isString()
    .trim()
    .notEmpty()
    .withMessage('User ID is required')
];

const batchUpdateRules: ValidationChain[] = [
  body('userIds')
    .isArray()
    .withMessage('userIds must be an array')
    .notEmpty()
    .withMessage('userIds cannot be empty'),
  body('data')
    .isObject()
    .withMessage('data must be an object')
    .notEmpty()
    .withMessage('data cannot be empty')
];

const searchRules: ValidationChain[] = [
  query('query')
    .optional()
    .isString()
    .trim(),
  query('limit')
    .optional()
    .isInt({ min: 1, max: 100 })
    .withMessage('Limit must be between 1 and 100')
];

export const validateUserCreation = createValidation(userCreationRules);
export const validateUserUpdate = createValidation(userUpdateRules);
export const validateUserId = createValidation(userIdRules);
export const validateBatchUpdate = createValidation(batchUpdateRules);
export const validateUserSearch = createValidation(searchRules);

export const validateUserOperation = {
  creation: withValidation(userCreationRules),
  update: withValidation(userUpdateRules),
  id: withValidation(userIdRules),
  batchUpdate: withValidation(batchUpdateRules),
  search: withValidation(searchRules)
};
